package cn.wolfcode.service.impl;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.AccountTransaction;
import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.mapper.AccountTransactionMapper;
import cn.wolfcode.mapper.UsableIntegralMapper;
import cn.wolfcode.service.IUsableIntegralService;
import cn.wolfcode.web.msg.IntergralCodeMsg;
import com.alibaba.fastjson.JSONObject;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.LocalTCC;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by lanxw
 */
@Service
public class UsableIntegralServiceImpl implements IUsableIntegralService {
    @Autowired
    private UsableIntegralMapper usableIntegralMapper;
    @Autowired
    private AccountTransactionMapper accountTransactionMapper;


    @Override
    public void decrIntegralTry(OperateIntergralVo vo, BusinessActionContext context) {
        AccountTransaction accountTransaction = new AccountTransaction();
        accountTransaction.setTxId(context.getXid()); // 全局事务id
        accountTransaction.setActionId(context.getBranchId()); // 分支事务id
        accountTransaction.setUserId(vo.getUserId()); //用户id
        Date now = new Date();
        accountTransaction.setGmtCreated(now); // 方法执行记录创建时间
        accountTransaction.setGmtModified(now); // 方法执行记录修改时间
        accountTransaction.setAmount(vo.getValue()); // 操作的金额
        accountTransaction.setState(AccountTransaction.STATE_TRY); // 当前事务的状态,实现commit/cancel方法一个事务中只执行一次
        // 插入日志事务控制表
        accountTransactionMapper.insert(accountTransaction);
        // 进行积分冻结
        int effect = usableIntegralMapper.freezeIntergral(vo.getUserId(), vo.getValue());
        if (effect == 0) { // 积分不够
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_NOT_ENOUGH);
        }
        // 积分足够
    }

    @Override
    public void decrIntegralCommit(BusinessActionContext context) {
        AccountTransaction accountTransaction = accountTransactionMapper.get(context.getXid(), context.getBranchId());
        // 判断是否有日志记录
        if (accountTransaction != null) { // 有日志记录
            // 判断日志记录的状态
            if (AccountTransaction.STATE_TRY == accountTransaction.getState()) { // try方法正常执行,执行commit
                // 从上下文中取出 vo 对象
                JSONObject jsonObject = (JSONObject) context.getActionContext("operateIntergralVo");
                OperateIntergralVo vo = jsonObject.toJavaObject(OperateIntergralVo.class);
                // 真实的扣减金额
                usableIntegralMapper.commitChange(vo.getUserId(),vo.getValue());
                // 修改日志记录的状态
                accountTransactionMapper.updateAccountTransactionState(context.getXid(), context.getBranchId(), AccountTransaction.STATE_COMMIT, AccountTransaction.STATE_TRY);
            }else { // 不是初始化状态,不做事情
            }
        }else { // 没有日志记录,不做事情
            //    1.框架出问题
            //    2.收到将数据库的这个记录删除掉.
            //    不是正常逻辑,记录日志排查就可以了>
        }
    }

    @Override
    public void decrIntegralRollback(BusinessActionContext context) {
        AccountTransaction accountTransaction = accountTransactionMapper.get(context.getXid(), context.getBranchId());
        // 从上下文中取出 vo 对象
        JSONObject jsonObject = (JSONObject) context.getActionContext("operateIntergralVo");
        OperateIntergralVo vo = jsonObject.toJavaObject(OperateIntergralVo.class);
        if (accountTransaction != null) { // 有日志记录
            // 判断日志记录的状态
            if (AccountTransaction.STATE_TRY == accountTransaction.getState()) { // 初始化状态,执行cancel
                // 解冻冻结金额
                usableIntegralMapper.unFreezeIntergral(vo.getUserId(),vo.getValue());
                // 修改日志记录的状态
                accountTransactionMapper.updateAccountTransactionState(context.getXid(), context.getBranchId(), AccountTransaction.STATE_CANCEL, AccountTransaction.STATE_TRY);
            }else { // 已经执行过回滚,重复回滚
                // 不做处理
            }
        }else { // 没有日志记录,属于空回滚或悬挂状态
            accountTransaction.setTxId(context.getXid());//全局事务ID
            accountTransaction.setActionId(context.getBranchId());//分支事务ID
            Date now = new Date();
            accountTransaction.setGmtCreated(now);//创建时间
            accountTransaction.setGmtModified(now);//修改时间
            accountTransaction.setUserId(vo.getUserId());//对应用户ID
            accountTransaction.setAmount(vo.getValue());//操作的金额
            accountTransaction.setState(AccountTransaction.STATE_CANCEL);
            accountTransactionMapper.insert(accountTransaction);
        }
    }


    @Override
    public int addIntegral(OperateIntergralVo vo) {
        return usableIntegralMapper.addIntegral(vo.getUserId(),vo.getValue());
    }
}
